package rsj.service.export.product;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import common.util.DateTimeFormatterUtil;
import rsj.api.org.entity.UsageReportParam;
import rsj.api.product.entity.ExportProductCurrentTable;
import rsj.service.export.IExportTemplateMethod;
import rsj.service.usage.product.IProductCalculateUsage;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 产品管理-导出当前环境表格
 *
 * @author yuanqinglong
 * @since 2021/3/5 15:34
 */
public interface IProductExportCurrentTable extends IExportTemplateMethod, IProductCalculateUsage {


    /**
     * 导出当前表格sql
     *
     * @param usageReportParam 参数
     * @return sql
     */
    static String exportCurrentTableQueryStatement(UsageReportParam usageReportParam) {
        String statDate = Optional.ofNullable(usageReportParam.getStatDate()).map(localDate -> "'" +
                DateTimeFormatterUtil.localDateFormatterToStringDate(usageReportParam.getStatDate()) + "'").orElse("stat_date");

        String sql = " SELECT stat_prod_uid,stat_prod_name,stat_org_id,stat_org_sname,sum(stat_useamount::INTEGER) as stat_useamount," +
                " CONCAT('截至',MAX(" + statDate + ")) AS stat_date " +
                " FROM sys.sys_stat " +
                " WHERE stat_env = #{environment} AND stat_prod_uid = #{statProdUid} ";
        if (Objects.nonNull(usageReportParam.getStatDate())) {
            sql += " AND stat_date < #{statDate} ";
        }
        sql += " GROUP BY stat_prod_uid,stat_prod_name,stat_org_id,stat_org_sname ";

        return sql;
    }


    /**
     * 将生成的文件写入本地
     *
     * @param jsonString 查询的数据
     * @param sheetName  导出的工作表名称
     * @return 写入文件的路径
     */
    @Override
    default OutputStream writeDataToTheOutputStream(String jsonString, String sheetName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        List<ExportProductCurrentTable> downloadExportEntities = JSON.parseArray(jsonString, ExportProductCurrentTable.class);
        EasyExcelFactory.write(outputStream, ExportProductCurrentTable.class).autoCloseStream(true).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(downloadExportEntities);
        return outputStream;
    }


    /**
     * 写数据到excel
     *
     * @param jsonData    json数据
     * @param excelWriter 优秀的作家
     * @param sheetNum    表num
     */
    @Override
    default void writeDataToTheExcelWriter(String jsonData, ExcelWriter excelWriter, int sheetNum) {
        WriteSheet writeSheet = EasyExcelFactory.writerSheet(sheetNum).head(ExportProductCurrentTable.class).build();
        excelWriter.write(JSON.parseArray(jsonData, ExportProductCurrentTable.class), writeSheet);
    }
}
